package dviz.visualSystem.impl;

import java.util.Map;

public class LinearInterpolate implements ValueInterpolate {
	private float estimateInterval;
	private float alpha;
	private float adaptFactor;

	private float interval;
	private double valueA;
	private double valueB;
	private boolean extrapolate;

	public LinearInterpolate() {
		alpha = -1;
		estimateInterval = 1;
		adaptFactor = 0.5f;
	}

	@Override
	public void addValue(Object value) {
		double v = new Double(value.toString());
		if (alpha == -1)
			valueB = v;
		estimateInterval = estimateInterval * (1.0f - adaptFactor)
				+ adaptFactor * interval;
		valueA = valueB;
		valueB = v;
		alpha = 0;
		interval = 0;
	}

	@Override
	public Object getValue() {
		if (!extrapolate && alpha > 1)
			return valueB;
		return valueB * alpha + valueA * (1f - alpha);
	}

	@Override
	public void setProperty(Map<String, String> property) {
		if (property.get("adaptFactor") != null)
			adaptFactor = new Float(property.get("adaptFactor"));
		if (property.get("extrapolate") != null)
			extrapolate = new Boolean(property.get("extrapolate"));
		if (property.get("estimateInterval") != null)
			estimateInterval = new Float(property.get("estimateInterval"));
	}

	@Override
	public void update(float fpt) {
		interval += fpt;
		if (estimateInterval != 0)
			alpha = interval / estimateInterval;
		else
			alpha = 1;
	}

}
